jQuery(function () {

	selectRegion = function(e){
        //window.location = getHeaderDestinationUrl();
       $.ajax({
        	url: getHeaderDestinationUrl(),
        	success: function(data){
        		updateSelectableCountries(data);
        		updateSelected(data);
        	}
        })
    }

	selectCountry = function(e){
        //window.location = getHeaderDestinationUrl();
        $.ajax({
        	url: getHeaderDestinationUrl(),
        	success: function(data){
        		updateSelectableStates(data);
        		updateSelected(data);
        	}
        })
    }
	
	updateSelectableCountries = function(data){
		$('#hotelDirectoryCountry').replaceWith( $(data).find('#hotelDirectoryCountry') )
		updateSelectableStates(data);
		
		//rebind the newly added country drop down
	    $('#hotelDirectoryCountry').bind('change', selectCountry);
	}
	
	updateSelectableStates = function(data){
		$('#hotelDirectoryState').replaceWith( $(data).find('#hotelDirectoryState') )
	}
	
	updateSelected = function(data){
		$('#selectedAreas').replaceWith( $(data).find('#selectedAreas') )
	}
	
    $('#hotelDirectoryRegion').bind('change', selectRegion);
    $('#hotelDirectoryCountry').bind('change', selectCountry);
    
    
    getCurrentLocation = function(e){
        navigator.geolocation.getCurrentPosition(
        function(position){
            
            var url = $('#searchUrl').val();
            url = url +"&latitude="+position.coords.latitude;
            url = url +"&longitude="+position.coords.longitude;
            
            //console.log("got near me search :"+url);
            
            window.location = url;
        },function(error){
            handleError(error,e);
        });
    }
    
    $('#findHotelsNearMe').bind('click',getCurrentLocation);

	
    getHeaderDestinationUrl = function(){
        var selectedRegion = $('#hotelDirectoryRegion').val();
    	var selectedCountry = $('#hotelDirectoryCountry').val();
    	var selectedState = $('#hotelDirectoryState').val();
    	var url = window.location.pathname+"?regionName="+selectedRegion+"&country="+selectedCountry+"&state="+selectedState;
		
		//console.log("destination Url = "+url);
		
		return url;
	}
    
    getDestinationUrl = function(onlyNewHotels){
    	var url = $('#hotelDirectoryState option:selected').attr('link');
		if(!url || url == 'all'){
			url = $('#hotelDirectoryCountry option:selected').attr('link');
		}
		if(!url || url == 'all'){
			url = $('#hotelDirectoryRegion option:selected').attr('link');
		}
		//console.log("destination Url = "+url);
		//console.log("newHotels value = "+onlyNewHotels);
		
		return urlForNewHotels(url, onlyNewHotels);
    }
    
    getHotelCategoryFilter = function(){
    	var hotelCategoryField = $('#hotelCategoryFilter');
    	var hotelCategoryValue = (hotelCategoryField.length > 0 && hotelCategoryField.val() != '' && hotelCategoryField.val() > 0) ? '?categoryFilter='+hotelCategoryField.val() : '' ;
    	return hotelCategoryValue;
    }
    
    urlForNewHotels = function(url, onlyNewHotels){
    	if(onlyNewHotels){
			//replace 'hotels' with 'new-hotels' in url
			return url.replace("directory/hotels","directory/new-hotels");
		}
    	return url;
    }
        
    getFilters = function(){
    	
    	var selectedAmenityFilters="";
    	$('#FilterGroup_HotelType .amenityCheckBox')
    		.filter( function(i){ return $(this).is(':checked') } )
    		.each(function(i,e){ selectedAmenityFilters = selectedAmenityFilters + e.value +'|'; });
    	if(selectedAmenityFilters){
    		selectedAmenityFilters = selectedAmenityFilters.substring(0, selectedAmenityFilters.length-1);
    	}

    	var selectedPropertyFilter="";
    	$('#FilterGroup_HotelType .propertyCheckBox')
    		.filter( function(i){ return $(this).is(':checked') } )
    		.each(function(i,e){ selectedPropertyFilter = selectedPropertyFilter + e.value +'|'; });
    	if(selectedPropertyFilter){
    		selectedPropertyFilter = selectedPropertyFilter.substring(0, selectedPropertyFilter.length-1);
    	}
    	
    	var selectedBrand = $('#FilterGroup_Brands .brandFilterRadio:checked').val();
    	if(selectedBrand === undefined){selectedBrand=""};
    	var selectedCategory = $('#FilterGroup_Categories .categoryFilterRadio:checked').val();
    	if(selectedCategory === undefined){selectedCategory=""};
    	
    	var filters = new Array();
    	if(selectedAmenityFilters){
    		filters.push("amenityFilter=" + selectedAmenityFilters)
    	}
    	if(selectedPropertyFilter){
    		filters.push("propertyFilter=" + selectedPropertyFilter)
    	}
    	if(selectedBrand){
    		filters.push("brandFilter=" + selectedBrand)
    	}
    	if(selectedCategory){
    		filters.push("categoryFilter=" + selectedCategory)
    	}
    	
    	return filters.join("&");
    }
    
	searchDirectory = function(){
		
		//console.log( $('#regionSelected').val() );
		
		var url = getDestinationUrl( $('#newHotels').is(':checked') );
		
		//append hotel category filter on initial search if applicable
		url += getHotelCategoryFilter();

		//console.log("getting results from "+url);
		
		searchDirectoryFromUrl(url);
	}
	
	filterSearchDirectory = function(){

		var url = createFilterDirectoryUrl();
		
		//console.log("getting results from \""+url+"\"");
		
		searchDirectoryFromUrl(url);
		
	}
	
	createFilterDirectoryUrl = function(){
		var normalUrl = window.location.pathname;
		if(normalUrl.indexOf('directory/new-hotels') !== -1){
			normalUrl = normalUrl.replace("directory/new-hotels","directory/hotels");
		}
		var url = urlForNewHotels( normalUrl, $('#newHotelsRefine').is(':checked') );
		var filters = getFilters();
		//console.log("got filters "+filters);
		if(filters){
			url = url + "?" + filters;
		}
		
		return url;
	}
	
	updateFilterCounts = function(){

		var url = createFilterDirectoryUrl();
		
		//console.log("getting results from \""+url+"\"");
		
		$.ajax({
        	url: url,
        	success: function(data){
        		//console.log( $(data).find("#directoryResults").html() );
        		//console.log($(data).find(".filterListItem").html());
        		$(data).find('.filterListItem').each( function(i, o){
        			//console.log( o.id +" has "+$(o).find('.filterHotelCount').html());
        			$( "#"+o.id+" .filterHotelCount" ).html($(o).find('.filterHotelCount').html());
        			
        			//update disabled checkboxes
        			if($(o).find('.filterHotelCheckbox  .filterCheckbox').attr('disabled')){
            			$( "#"+o.id+" .filterHotelCheckbox .filterCheckbox" ).attr('disabled', 'disabled');
            			$( "#"+o.id+" .filterHotelCheckbox.checkBoxDiv" ).removeClass('checkBoxDiv').addClass('checkBoxDivDisabled');
        			}
        			else{
            			$( "#"+o.id+" .filterHotelCheckbox .filterCheckbox" ).removeAttr('disabled');
            			$( "#"+o.id+" .filterHotelCheckbox.checkBoxDivDisabled" ).removeClass('checkBoxDivDisabled').addClass('checkBoxDiv');
        			}

        			if($(o).find('.filterHotelRadio  .filterRadio').attr('disabled')){
            			$( "#"+o.id+" .filterHotelRadio .filterRadio" ).attr('disabled', 'disabled');
            			$( "#"+o.id+" .filterHotelRadio .radioButton" ).removeClass('radioButton').addClass('radioButtonDisabled');
        			}
        			else{
            			$( "#"+o.id+" .filterHotelRadio .filterRadio" ).removeAttr('disabled');
            			$( "#"+o.id+" .filterHotelRadio .radioButtonDisabled" ).removeClass('radioButtonDisabled').addClass('radioButton');
        			}
        			
        		})
        		
        	}
        })
	}
	
	searchDirectoryFromUrl = function(url){
		window.location = url;
        /*
        $.ajax({
        	url: url,
        	success: function(data){
        		//console.log( $(data).find("#directoryResults").html() );
        		$('#directoryResults').html( $(data).find('#directoryResults').html() )
        		$('#directoryResults').show();

        		$('#filters').html( $(data).find('#filters').html() )
        		
        		hideDestinationSearch();
        		hideFilterSearch();
        		
        		hideAllPropertyDetails();
        		$('.propertyLinkHead').bind('click',showPropertyDetails);
        		
        		$('#filterResults').bind('click',addFilterResults)
        	}
        }) */
    }
	
	hideDestinationSearch = function(){
		$('#directorySearch').hide();
	}
	hideFilterSearch = function(){
		$('#filters').hide();
	}
	hideDirectoryResults = function(){
		$('#directoryResults').hide();
	}
	
	addFilterResults = function(){
        $('#header-directory').hide();
        $('#header-refine').show();
		$('#filters').show();
		hideDirectoryResults();
	}
	
	resetFilters = function(){
		$('#FilterGroup_HotelType .amenityCheckBox').removeAttr('checked')
		$('#FilterGroup_HotelType .propertyCheckBox').removeAttr('checked')
		//$('#brand_all').attr('checked', 'checked');
		$('#category_all').attr('checked', 'checked');
		updateFilterCounts();
	}
	
	hideAllPropertyDetails = function(){
		$('.propertyLinkHead>.searchResultsPropertyBox').hide();
    }
	showPropertyDetails = function(e){
		$(this).next('.searchResultsPropertyBox').toggle();
	}
	
	var gotoHotelLocation = function(e){
		var link = $(this).parent().parent().parent().parent().find('a.propertyLink').attr('href');
		window.location.href = link;
	}

	$('#findHotels').bind('click', searchDirectory);
	hideAllPropertyDetails();
	$('.propertyLinkHead').bind('click',showPropertyDetails);
	$('#filterResults').bind('click',addFilterResults);
	$('#applyFilters').bind('click',filterSearchDirectory);
	$('#backToResults').bind('click',function(){
        $('#header-directory').show();
        $('#header-refine').hide();
		$('#directoryResults').show();
		hideFilterSearch();
	});
	$('#resetFilters').bind('click', resetFilters);
	$('.filterCheckbox').bind('click', updateFilterCounts);
	$('#newHotelsRefine').bind('click', resetFilters);
	$('.filterRadio').bind('click', updateFilterCounts);
	$(".activeProperty .address, .activeProperty .detailThumb").bind('click', gotoHotelLocation);

    // if user happens to hit back button this will re-populate dropdown selections
    if ($('#hotelDirectoryRegion').val() !== 'all') { selectRegion(); }
    if ($('#hotelDirectoryCountry').val() !== 'all') { selectCountry(); }
});